package com.yhyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.yhyl.common.core.domain.AjaxResult;
import com.yhyl.common.exception.base.BaseException;
import com.yhyl.common.utils.DateUtils;
import com.yhyl.nursing.Dto.CheckInApplyDto;
import com.yhyl.nursing.Dto.CheckInContractDto;
import com.yhyl.nursing.Dto.CheckInElderDto;
import com.yhyl.nursing.domain.*;
import com.yhyl.nursing.mapper.*;
import com.yhyl.nursing.util.CodeGenerator;
import com.yhyl.nursing.vo.CheckInConfigVo;
import com.yhyl.nursing.vo.CheckInDetailVo;
import com.yhyl.nursing.vo.CheckInElderVo;
import com.yhyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import com.yhyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-15
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {

        return save(checkIn) == true? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {

        return updateById(checkIn) == true ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) == true ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) == true ? 1 : 0;
    }
     @Transactional
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
         try {
             //判断老人是否入住
             //通过查询老人的身份证号查询
             //1.创一个lamda查询类
             LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
             //2.添加查询条件 where id_card_no = #{idCardNo} and status = 1
             elderLambdaQueryWrapper.eq(Elder::getIdCardNo,checkInApplyDto.getCheckInElderDto().getIdCardNo());
             elderLambdaQueryWrapper.eq(Elder::getStatus,1);
             //3.查询  select .....
             Elder elder = elderMapper.selectOne(elderLambdaQueryWrapper);
             if(ObjectUtil.isNotEmpty(elder)){
                 throw new BaseException("该老人已入住");
             }

             //更新床位状态为已入住
             Bed bed =  bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
             bed.setBedStatus(1);
             bedMapper.updateById(bed);
             //新增或更新老人
             elder =  InsertorUpdateElder(bed, checkInApplyDto.getCheckInElderDto());
             //新增签约办理 合同
             String contractNo= "HT" + CodeGenerator.generateContractNumber();
             insertContract(elder,contractNo,checkInApplyDto);

             //新增入住配置
             CheckIn checkin =inserCheckIn(elder,bed,checkInApplyDto);

             //新增入住配置
             insertCheckInConfig(checkin,checkInApplyDto);
         } catch (BaseException e) {
             throw new BaseException("入住失败");
         }
     }
     //注意是入住id
    @Override
    public CheckInDetailVo detail(Long id) {
        //查询入住信息
     CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //查询老人信息
        CheckIn checkIn = checkInMapper.selectById(id);
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());

        //赋值
        if(ObjectUtil.isNotEmpty(elder)) {
            CheckInElderVo checkInElderVo = new CheckInElderVo();
            BeanUtils.copyProperties(elder, checkInElderVo);
            //设置老人年龄
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            checkInElderVo.setAge(Period.between(LocalDate.parse(elder.getBirthday(), formatter), LocalDate.now()).getYears());
            checkInDetailVo.setCheckInElderVo(checkInElderVo);
        }
        //查询合同
         LambdaQueryWrapper<Contract> contractLambdaQueryWrapper = new LambdaQueryWrapper<>();
         contractLambdaQueryWrapper.eq(Contract::getElderId,elder.getId());
         Contract contract = contractMapper.selectOne(contractLambdaQueryWrapper);
         checkInDetailVo.setContract(contract);
        //查询配置
        CheckInConfigVo  checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkIn,checkInConfigVo);
        LambdaQueryWrapper<CheckInConfig> checkInConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
        checkInConfigLambdaQueryWrapper.eq(CheckInConfig::getCheckInId,checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigLambdaQueryWrapper);
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //转换家属列表
        List<ElderFamilyVo> list = JSONUtil.toList(JSONUtil.parseArray(checkIn.getRemark()), ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(list);

        //整合数据返回
        return checkInDetailVo;
    }

    private void insertCheckInConfig(CheckIn checkin, CheckInApplyDto checkInApplyDto) {
        //属性拷贝
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkin.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn inserCheckIn(Elder elder, Bed bed, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStatus(0);
        checkIn.setBedNumber(bed.getBedNumber());
        //家属列表，转换为json存为remark字段
        checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void insertContract(Elder elder, String contractNo, CheckInApplyDto checkInApplyDto) {
        //属性拷贝
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto,contract);
        //老人相关的，合同编号，状态，实践
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setContractNumber(contractNo);
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        //设置状态
        //合同开始时间在当前时间之后，则状态为正常
        Integer status = startDate.isAfter(LocalDateTime.now())? 1: 0;
        contract.setStatus(status);
        //保存合同
        contractMapper.insert(contract);
    }

    private Elder InsertorUpdateElder(Bed bed, CheckInElderDto checkInElderDto) {
        //核心逻辑，当我们拿到老人的新的信息的时候，要去通过判断身份证号和状态去判断是更新，还是插入，用来防止老人入住重复
        //新老人信息准备
        Elder elder = new Elder();
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        BeanUtils.copyProperties(checkInElderDto,elder);
        elder.setStatus(1);
        //查询旧老人信息（拿到数据判断更新还是插入）
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo());
        elderLambdaQueryWrapper.eq(Elder::getStatus,1);
        Elder elderOb = elderMapper.selectOne(elderLambdaQueryWrapper);
        if(ObjectUtils.isNotEmpty(elderOb)){
            //修改
            elderMapper.updateById(elder);
        }else {
            //新增
            elderMapper.insert(elder);
        }
        return elder;
    }


}
